package com.antkit.mark.ak.gd;

import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * @author Mark
 * @Date on 2019/1/31
 **/
public class MediaPlayerManager {

    private static MediaPlayerManager instance;
    public static MediaPlayerManager getInstance(){

        if (instance==null){
            instance = new MediaPlayerManager();
        }

        return instance;
    }

    public MediaPlayer mediaPlayer = new MediaPlayer();

    public MediaPlayerManager init(AssetFileDescriptor fd) {
        // 设置指定的流媒体地址
        try {
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
        } catch (IOException e) {
            e.printStackTrace();
        }
//        // 设置音频流的类型
//        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        return this;
    }

    public MediaPlayerManager setOnPreparedListener(MediaPlayer.OnPreparedListener onPreparedListener) {

        if (onPreparedListener != null) {
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    // 装载完毕 开始播放流媒体
                    mediaPlayer.start();
                    onPreparedListener.onPrepared(mp);
                }
            });
        }

        return this;
    }

    public MediaPlayerManager setOnCompletionListener(MediaPlayer.OnCompletionListener onCompletionListener) {
        if (onCompletionListener!=null){

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 在播放完毕被回调
                    onCompletionListener.onCompletion(mp);
                }
            });
        }
        return this;
    }
}
